<template>
  <div class="chart-container">
    <div class="chart-header">
      <el-date-picker
        v-model="selectedTime"
        type="datetime"
        placeholder="选择功图采集时间"
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
        @change="handleTimeChange"
      />
      <el-button type="primary" @click="fetchChartData">查询</el-button>
    </div>
    <div ref="chartRef" class="chart" v-loading="loading"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

const props = defineProps({
  height: {
    type: String,
    default: '600px'
  }
})

const chartRef = ref(null)
const chart = ref(null)
const loading = ref(false)
const selectedTime = ref('')

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  // 确保容器有尺寸
  if (!chartRef.value.clientWidth || !chartRef.value.clientHeight) {
    chartRef.value.style.width = '100%'
    chartRef.value.style.height = '400px'
  }

  if (chart.value) {
    chart.value.dispose()
  }

  chart.value = echarts.init(chartRef.value)
  
  // 设置默认配置
  const option = {
    title: {
      text: '功图数据散点图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function(params) {
        const point = params[0] || params[1]
        return `X: ${point.data[0]}<br/>Y: ${point.data[1]}`
      }
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: 'X轴',
      nameLocation: 'center',
      nameGap: 30,
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          color: '#ddd'
        }
      },
      axisLine: {
        show: true
      }
    },
    yAxis: {
      type: 'value',
      name: 'Y轴',
      nameLocation: 'center',
      nameGap: 40,
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          color: '#ddd'
        }
      },
      axisLine: {
        show: true
      }
    },
    series: [
      {
        name: '数据点',
        type: 'scatter',
        symbolSize: 8,
        itemStyle: {
          color: '#409EFF'
        },
        data: []
      },
      {
        name: '连线',
        type: 'line',
        showSymbol: false,
        data: [],
        lineStyle: {
          width: 2,
          color: '#409EFF',
          opacity: 0.5
        },
        smooth: false
      }
    ]
  }
  
  chart.value.setOption(option)
}

// 获取功图数据
const fetchChartData = async () => {
  if (!selectedTime.value) {
    ElMessage.warning('请选择功图采集时间')
    return
  }

  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await fetch('/api/dashboard/chart', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        time: selectedTime.value,
        limit: 250
      })
    })

    if (!response.ok) {
      throw new Error('获取功图数据失败')
    }

    const result = await response.json()
    if (result.code === 200) {
      const { x = [], y = [] } = result.data
      // 将 x 和 y 数组组合成坐标点数组
      const data = x.map((xValue, index) => [xValue, y[index]])
      
      // 更新图表数据，同时更新散点和连线
      chart.value.setOption({
        series: [
          {
            // 更新散点数据
            type: 'scatter',
            data: data
          },
          {
            // 更新连线数据
            type: 'line',
            data: data
          }
        ]
      })
    } else {
      throw new Error(result.message || '获取功图数据失败')
    }
  } catch (error) {
    console.error('获取功图数据失败:', error)
    ElMessage.error(error.message)
  } finally {
    loading.value = false
  }
}

// 更新图表数据
const updateChartData = (data) => {
  if (!chart.value) return
  
  chart.value.setOption({
    series: [
      {
        type: 'scatter',
        data: data
      },
      {
        type: 'line',
        data: data
      }
    ]
  })
}

// 处理时间选择变化
const handleTimeChange = () => {
  if (selectedTime.value) {
    fetchChartData()
  }
}

// 监听窗口大小变化
const handleResize = () => {
  if (chart.value) {
    chart.value.resize()
  }
}

onMounted(() => {
  nextTick(() => {
    initChart()
  })
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (chart.value) {
    chart.value.dispose()
  }
})

// 导出方法供父组件调用
defineExpose({
  updateChartData
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.chart {
  width: 100%;
  height: v-bind('props.height');
}
</style>
